#include "ScnsBeep.c.h"

#if defined(SCNS_BEEP_ENABLE)&&SCNS_BEEP_ENABLE==1

#include "tim.h"

ScnsStatus scnsBspBeepInit(void)
{
#if defined(SCNS_BSP_BEEP_PIANO_ENABLE)&&SCNS_BSP_BEEP_PIANO_ENABLE==1
    HAL_TIM_PWM_Start(&htim2,TIM_CHANNEL_1);
#endif
    return SCNS_STATUS_OK;
}

void scnsBspBeepSet(ScnsBeepTone status)
{
#if defined(SCNS_BSP_BEEP_PIANO_ENABLE)&&SCNS_BSP_BEEP_PIANO_ENABLE==1
    if(status==SCNS_BEEP_TONE_OFF)
        __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,0);
    else
    {
        const uint32 freq=status;
        static const uint32 system_clock=120000000;
        uint16 freq_div=((system_clock/freq)>>15);
        uint16 period_temp=(system_clock/freq/(freq_div+1));
        uint16 match_temp=(uint16)(period_temp*(0.75));
        if(match_temp==period_temp)
            match_temp+=1;
        htim2.Instance->ARR=period_temp;
        htim2.Instance->PSC=freq_div;
        __HAL_TIM_SET_COMPARE(&htim2,TIM_CHANNEL_1,match_temp);
    }
#else
    BEEP_GPIO_Port->BSRR=(status!=SCNS_BEEP_TONE_OFF)?(BEEP_Pin):(BEEP_Pin<<16);
#endif
}

#endif